from flask import render_template, session, current_app, g, jsonify, abort, request

from info import constants, db
from info.models import User, News, Comment, CommentLike
from info.modules.news import news_blue
from info.utils.common import user_login_data
from info.utils.response_code import RET


@news_blue.route('/comment_like', methods=["POST"])
@user_login_data
def comment_like():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    # 1.获取参数
    comment_id = request.json.get("comment_id")
    action = request.json.get("action")

    # 2.校验参数
    if not all([comment_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in (["add", "remove"]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")

    if not comment:
        return jsonify(errno=RET.NODATA, errmsg="数据不存在")

    if action == "add":
        comment_likes = CommentLike.query.filter(CommentLike.comment_id == comment_id,
                                                 CommentLike.user_id == user.id).first()
        if not comment_likes:
            comment_likes = CommentLike()
            comment_likes.comment_id = comment_id
            comment_likes.user_id = user.id
            db.session.add(comment_likes)

            comment.like_count += 1

        else:
            comment_likes = CommentLike.query.filter(CommentLike.comment_id == comment_id,
                                                     CommentLike.user_id == user.id).first()
            if comment_likes:
                db.session.delete(comment_likes)
                comment.like_count -= 1

    return jsonify(errno=RET.OK, errmsg="操作成功")


@news_blue.route('/news_comment', methods=["POST"])
@user_login_data
def news_comment():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    # 1.获取参数
    news_id = request.json.get("news_id")
    comment_str = request.json.get("comment")
    parent_id = request.json.get("parent_id")

    # 2.校验参数
    if not all([news_id, comment_str]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="数据不存在")

    # 3.初始化模型，保存数据
    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news_id
    comment.content = comment_str
    if parent_id:
        comment.parent_id = parent_id

    # 保存数据
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    # 返回响应
    return jsonify(errno=RET.OK, errmsg="操作成功", data=comment.to_dict())


@news_blue.route('/news_collect', methods=["POST"])
@user_login_data
def collect_news():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    # 1.获取参数
    news_id = request.json.get("news_id")
    action = request.json.get("action")
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in (["collect", "cancel_collect"]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 2.查询并添加
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="数据不存在")

    if action == "collect":
        user.collection_news.append(news)

    else:
        user.collection_news.remove(news)

    # 3.返回响应
    return jsonify(errno=RET.OK, errmsg="收藏成功")


@news_blue.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):
    user = g.user

    # # 1.获取当前用户登录的id
    # user_id = session.get("user_id", None)
    #
    # # 2.通过id获取用户的登录信息
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)

    # 1.获取当前页数据
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询错误")

    if not news:
        abort(404)

    # 2.更新点击量
    news.clicks += 1

    # 获取点击排行的数据
    news_list1 = []
    try:
        news_list1 = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    click_news_list = []
    for news2 in news_list1:
        click_news_list.append(news2.to_basic_dict())

    # 判断用户是否收藏过新闻，默认值是false
    is_collected = False
    if user:
        if news in user.collection_news:
            is_collected = True

    # 获取当前新闻的评论
    comments = None
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询失败")

    comment_like_ids = []
    if g.user:
        # 如果当前用户已登录
        try:
            comment_ids = [comment.id for comment in comments]
            if len(comment_ids) > 0:
                # 取到当前用户在当前新闻的所有评论点赞的记录
                comment_likes = CommentLike.query.filter(CommentLike.comment_id.in_(comment_ids),
                                                         CommentLike.user_id == g.user.id).all()
                # 取出记录中所有的评论id
                comment_like_ids = [comment_like.comment_id for comment_like in comment_likes]
        except Exception as e:
            current_app.logger.error(e)

    comment_list = []
    for item in comments:
        comment_dict = item.to_dict()
        comment_dict["is_like"] = False
        if item.id in comment_like_ids:
            comment_dict["is_like"] = True
        comment_list.append(comment_dict)

    data = {
        "news": news.to_dict(),
        "user": user.to_dict() if user else None,
        "click_news_list": click_news_list,
        "is_collected": is_collected,
        "comments": comment_list
    }
    return render_template("news/detail.html", data=data)
